package main

import (
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

// 声明全局数据库对象
var db *gorm.DB

// Product结构体定义商品表结构，对应MySQL中的product表
type Product struct {
	gorm.Model
	Code  string
	Price uint
}

// init函数初始化数据库连接
func init() {
	// 构建MySQL连接字符串，配置账号root和密码12345678
	dsn := "root:12345678@tcp(127.0.0.1:3306)/gorm?charset=utf8mb4&parseTime=True&loc=Local"
	var err error
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 禁用表名复数形式
		},
		// 新增日志配置
		Logger: logger.Default.LogMode(logger.Info), // 设置日志级别为Info
	})
	if err != nil {
		panic("failed to connect database")
	}
}

func main() {
	// 自动迁移，创建product表（使用全局db对象）
	db.AutoMigrate(&Product{})

	// 使用GORM插入数据（使用全局db对象） INSERT INTO `product` (`created_at`,`updated_at`,`deleted_at`,`code`,`price`) VALUES ('2025-03-17 11:26:15.123','2025-03-17 11:26:15.123',NULL,'F64',200)
	db.Create(&Product{Code: "F64", Price: 200})

	// 数据查询操作
	var product Product
	// 根据主键查询第一条记录 SELECT * FROM `product` WHERE `product`.`id` = 1 AND `product`.`deleted_at` IS NULL ORDER BY `product`.`id` LIMIT 1
	db.First(&product, 1)
	// 根据code字段查询记录 SELECT * FROM `product` WHERE code = 'D42' AND `product`.`deleted_at` IS NULL AND `product`.`id` = 1 ORDER BY `product`.`id` LIMIT 1
	db.First(&product, "code = ?", "D42")

	// 数据更新操作
	// 更新单个字段UPDATE `product` SET `price`=200,`updated_at`='2025-03-17 11:26:15.127' WHERE `product`.`deleted_at` IS NULL AND `id` = 1
	db.Model(&product).Update("Price", 200)
	// 更新多个字段（仅更新非零值字段）UPDATE `product` SET `updated_at`='2025-03-17 11:26:15.129',`code`='F42',`price`=200 WHERE `product`.`deleted_at` IS NULL AND `id` = 1
	db.Model(&product).Updates(Product{Price: 200, Code: "F42"})
	// 使用map更新多个字段 UPDATE `product` SET `code`='F42',`price`=200,`updated_at`='2025-03-17 11:26:15.131' WHERE `product`.`deleted_at` IS NULL AND `id` = 1
	db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})

	// 数据删除操作（软删除） UPDATE `product` SET `deleted_at`='2025-03-17 11:26:15.133' WHERE `product`.`id` = 1 AND `product`.`id` = 1 AND `product`.`deleted_at` IS NULL
	db.Delete(&product, 1)
}
